//
//  RegisterViewController.m
//  DianDangDai
//
//  Created by bhf on 2017/12/15.
//  Copyright © 2017年 bhf. All rights reserved.
//

#import "RegisterViewController.h"
#import "BMCell.h"
#import "UIButton+WebCache.h"
#import "HomePageDetailController.h"
@interface RegisterViewController ()<UITableViewDelegate, UITableViewDataSource,UITextFieldDelegate>
{
    NSString *_imgUUID;
    NSString *_imgURL;
    NSString *_phone;
    NSString *_pwd;
    NSString *_imgCode;
    NSString *_referrer;
    NSString *_msg;
}
@property (nonatomic, strong) NSArray *imgArray;
@property (nonatomic, strong) NSArray *titleArray;
@property (nonatomic, strong) NSArray *placeholderArray;

@end

@implementation RegisterViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    _imgArray = @[@"phone",@"password",@"inviter",@"graphic",@"identifying"];
    _titleArray = @[@"* 手机号",@"* 密　码",@"   邀请人",@"* 图形码",@"* 验证码"];
    _placeholderArray = @[@"请输入手机号",@"请输入密码6-16位字符",@"请输入推荐人手机号码(选填)",@"请输入图形码",@"请输入验证码"];
    [self setupViews];
    [self getImage];
    // Do any additional setup after loading the view.
}

- (void)getImage {
    NSString *urlString = [NSString stringWithFormat:@"%@OPT=1011",API_LOGIN_URL_STRING];
    [[CDHttpHelper defaultCDHttpHelper] get:urlString params:nil success:^(id responseObj) {
        NSDictionary *dict = [responseObj objectFromJSONData];
        NSLog(@"%@",dict);
        _imgUUID = dict[@"randomId"];
        _imgURL = dict[@"img"];
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        
    } showHUD:YES];
}

- (void)setupViews  {
    self.regist.layer.cornerRadius = self.regist.height/2;
}
- (IBAction)regist:(UIButton *)sender {
    NSString *urlString = [NSString stringWithFormat:@"%@OPT=1017&mobile=%@&pwd=%@&smsCode=%@&referrerName=%@",API_LOGIN_URL_STRING,_phone,_pwd,_msg,_referrer];
    NSLog(@"%@",urlString);
    [[CDHttpHelper defaultCDHttpHelper] post:urlString params:nil success:^(id responseObj) {
        NSDictionary *dict = [responseObj objectFromJSONData];
        NSLog(@"%@",dict);
        [self.view makeToast:dict[@"msg"]];
    } failure:^(NSError *error) {
        
    } showHUD:YES];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
#pragma mark - TableView Data Source

- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 5;
}



- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    NSString *identifier;
    
    switch (indexPath.row) {
        case 0:
            identifier = @"bm_cell_II";
            break;
        case 1:
            identifier = @"bm_cell_I";
            break;
        case 2:
            identifier = @"bm_cell_II";
            break;
        case 3:
            identifier = @"bm_cell_III";
            break;
        case 4:
            identifier = @"bm_cell_III";
            break;
        default:
            break;
    }
    
    
    BMCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:indexPath];
    cell.button.tag = 100+indexPath.row;
    cell.textField.delegate = self;
    cell.textField.tag = 100+indexPath.row;
    cell.image.image = [UIImage imageNamed:_imgArray[indexPath.row]];
    cell.name.text = _titleArray[indexPath.row];
    NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:_placeholderArray[indexPath.row] attributes:
                                      @{NSForegroundColorAttributeName:[UIColor whiteColor],
                                        NSFontAttributeName:cell.textField.font
                                        }];
  //  textField.attributedPlaceholder = attrString;
    cell.textField.attributedPlaceholder = attrString;
    cell.textField.tag = indexPath.row+100;
    
    if (indexPath.row == 3) {
        [cell.button sd_setImageWithURL:[NSURL URLWithString:_imgURL] forState:UIControlStateNormal placeholderImage:nil options:SDWebImageRefreshCached];
   
    }
    if (indexPath.row == 1
        || indexPath.row == 3) {
        cell.textField.keyboardType = UIKeyboardTypeDefault;
        cell.line.hidden = YES;
    }
    return cell;
}

- (IBAction)login:(UIButton *)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (IBAction)hidePwd:(UIButton *)sender {
    
}

- (IBAction)getMessage:(UIButton *)sender {
    if (sender.tag == 103) {
  
        NSIndexPath *indexPathA = [NSIndexPath indexPathForRow:3 inSection:0]; //刷新第0段第2行
        [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPathA,nil] withRowAnimation:UITableViewRowAnimationNone];

    } else if (sender.tag == 104) {
     
        
        __block int timeout= 119; //倒计时时间
        
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        
        dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
        
        dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
        
        dispatch_source_set_event_handler(_timer, ^{
            
            if(timeout<=0){ //倒计时结束，关闭
                
                dispatch_source_cancel(_timer);
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    //设置界面的按钮显示 根据自己需求设置
                    [sender setTitle:@"获取验证码" forState:0];
                    [sender setTitleColor:[UIColor colorWithHex:@"#FDDC00"] forState:UIControlStateNormal];
                    sender.userInteractionEnabled = YES;
                });
                
            }else{
                
                //            int minutes = timeout / 60;
                
                int seconds = timeout % 120;
                
                NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    //设置界面的按钮显示 根据自己需求设置
                    
                    [sender setTitle:[NSString stringWithFormat:@"%@S后获取",strTime] forState:UIControlStateNormal];
                    
                    sender.userInteractionEnabled = NO;
                    
                });
                
                timeout--;
                
            }
            
        });
        
        dispatch_resume(_timer);
        
        NSString *urlString = [NSString stringWithFormat: @"%@OPT=1014&mobile=%@&cCode=%@&randomId=%@",API_LOGIN_URL_STRING,_phone,_imgCode,_imgUUID];

        NSLog(@"%@",urlString);
        [[CDHttpHelper defaultCDHttpHelper] get:urlString params:nil success:^(id responseObj) {
            NSDictionary *dict = [responseObj objectFromJSONData];
            NSLog(@"%@",dict);
            [self.view makeToast:dict[@"msg"]];
        } failure:^(NSError *error) {
            
        } showHUD:YES];
    }
   
    
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    if (textField.tag == 100) {
        _phone = textField.text;
    } else if (textField.tag == 101) {
        _pwd = textField.text;
    } else if (textField.tag == 103) {
        _imgCode = textField.text;
    } else if (textField.tag == 102) {
        _referrer = textField.text;
    } else if (textField.tag == 104) {
        _msg = textField.text;
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (IS_IPHONE_5) {
        _bottomView.size = CGSizeMake(SCREEN_WIDTH, 200);
        return (SCREEN_HEIGHT-360)/5;
    } 
    return (SCREEN_HEIGHT-385)/5;
}
- (IBAction)xieyi:(UIButton *)sender {
    
    UIStoryboard *board = [UIStoryboard storyboardWithName:@"HomePage" bundle:[NSBundle mainBundle]];
    HomePageDetailController *hpdc = [board instantiateViewControllerWithIdentifier:@"hpdc"];
    hpdc.titleStr = @"注册协议";
    hpdc.hidesBottomBarWhenPushed = YES;
    [self showViewController:hpdc sender:self];
}

@end
